//
//  VCSelectCity.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/25.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VCCitySelect: VCBase {
    
    // uisearchBar
    private lazy var searchBar: UISearchBar = {
        let ui = UISearchBar()
        ui.backgroundColor = COLOR_LIGHT_WHITE3
        ui.frame = CGRect(x: 0, y: realHeight + MARGIN10, width: SCREEN_WIDTH, height: MARGIN50)
        return ui
    }()
    
    // 热点城市
    private lazy var hotCityView:HotCityView = {
        let ui = HotCityView()
        ui.delegate = self
        ui.backgroundColor = COLOR_LIGHT_WHITE3
        ui.frame = CGRect(x: 0, y: searchBar.frame.maxY, width: SCREEN_WIDTH, height: 380)
        return ui
    }()
    
    // tabliview
    private lazy var uitableview: UITableView = {
        let ui = UITableView()
        let uiY = searchBar.frame.maxY
        ui.backgroundColor = COLOR_LIGHT_WHITE3
        ui.frame = CGRect(x: 0, y: uiY, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - uiY)
        return ui
    }()
    
    // 重用ID
    private let ID = "tableview_cell_id"
    // 城市数据
    private var citys = CityInfo.shareInstance.getCityInfo()
    
    // MARK: 回调
    public var complete:((_ item:String) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_set()
        init_views()
        init_event()
    }
}

// MARK: HotCityView代理
extension VCCitySelect:HotCityViewDelegate {
    
    func returnCityName(city: String) {
       if let callback = complete {
            callback(city)
        }
        navigationController?.popViewController(animated: true)
    }
}

// MARK: tabliview代理
extension VCCitySelect:UITableViewDataSource,UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return citys.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let infos = citys[section].citys else {
            return 0
        }
        return infos.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: ID)
        }
        guard let citys = citys[indexPath.section].citys else {
            return cell!
            
        }
        cell?.backgroundColor = COLOR_LIGHT_WHITE3
        cell?.textLabel?.text = citys[indexPath.row]
        cell?.textLabel?.textColor = UIColor.gray
        cell?.textLabel?.font = UIFont.systemFont(ofSize: 13)
        return cell!
    }
    
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return (citys as NSArray).value(forKey: "title") as? [String]
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return MARGIN50
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        guard let title = citys[section].title else {
            return UIView()
        }
        let label = UITextField(str: title, size: 20)
        label.textColor = UIColor.black
        label.frame = CGRect(x: MARGIN, y: 0, width: MARGIN100, height: MARGIN40)
        label.backgroundColor = COLOR_LINE
        return label
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let citys = citys[indexPath.section].citys else {
            return
        }
        let city = citys[indexPath.row]
        if let callback = complete {
            callback(city)
        }
        navigationController?.popViewController(animated: true)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
}

// MARK: 搜索代理
extension VCCitySelect:UISearchBarDelegate {
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.text = ""
        // 显示热点城市
        UIView.animate(withDuration: 0.3) {
            self.uitableview.tableHeaderView = self.hotCityView
        }
        view.endEditing(true)
    }
    
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        // 隐藏热点城市
        UIView.animate(withDuration: 0.3) {
            self.uitableview.tableHeaderView = UIView()
            // 恢复城市信息
            searchBar.text = ""
            self.citys = CityInfo.shareInstance.getCityInfo()
            self.uitableview.reloadData()
        }
        return true
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        // 数字进行拦截
        if isNotChar(str: searchText) {
            searchBar.text = ""
            return
        }
        // 第一个字母大写
        searchBar.text = searchText.uppercased()
        // 第二个字母输不上
        if let textCount = searchBar.text?.count,textCount > 1 {
            searchBar.text = searchBar.text?.suffix(1).description
            return
        }
        // 查找对应字母城市
        updateInputCitys()
    }
    
    func updateInputCitys() -> Void {
        for city in citys {
            if let cTitle = city.title,let sTitle = searchBar.text,cTitle.elementsEqual(sTitle) {
                citys = [city]
                view.endEditing(true)
                self.uitableview.reloadData()
            }
        }
    }
}

extension VCCitySelect {
    
    private func init_event() -> Void {
        // 设置searchbar属性
        searchBar.delegate = self
        searchBar.searchBarStyle = .minimal
        searchBar.keyboardType = .asciiCapable
        searchBar.placeholder = "请输入城市的首字母"
        searchBar.setValue("取消", forKey: "cancelButtonText")
        searchBar.setShowsCancelButton(true, animated: true)
        if #available(iOS 13.0, *) {
            searchBar.searchTextField.font = UIFont.systemFont(ofSize: 13)
        }
        // 设置uitablview属性
        uitableview.delegate = self
        uitableview.dataSource = self
        uitableview.rowHeight = MARGIN60
        uitableview.tableHeaderView = hotCityView
        uitableview.register(UITableViewCell.self, forCellReuseIdentifier: ID)
    }
    
    private func init_views() -> Void {
        view.addSubview(searchBar)
        view.addSubview(uitableview)
    }
    
    private func init_set() -> Void {
        // 背景颜色
        view.backgroundColor = UIColor.white
    }
}

